package com.zrwl.poscloud.core.restapi.authorization;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zrwl.poscloud.base.entity.*;
import com.zrwl.poscloud.base.enums.EMenuType;
import com.zrwl.poscloud.base.enums.EMessageModelType;
import com.zrwl.poscloud.base.enums.EStatus;
import com.zrwl.poscloud.base.global.Constants;
import com.zrwl.poscloud.commons.config.jwt.Audience;
import com.zrwl.poscloud.commons.config.jwt.JwtTokenUtil;
import com.zrwl.poscloud.commons.feign.ProxyFeignClient;
import com.zrwl.poscloud.commons.utils.*;
import com.zrwl.poscloud.core.global.SQLConf;
import com.zrwl.poscloud.xo.global.MessageConf;
import com.zrwl.poscloud.xo.global.RedisConf;
import com.zrwl.poscloud.xo.global.SysConf;
import com.zrwl.poscloud.xo.service.*;
import com.zrwl.poscloud.xo.utils.WebUtil;
import com.zrwl.poscloud.xo.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 登录管理 RestApi【为了更好地使用security放行把登录管理放在AuthRestApi中】
 *
 * @author limbo
 * @date 2018-10-14
 */
@RestController
@RefreshScope
@RequestMapping("/auth")
@Api(value = "登录相关接口", tags = {"登录相关接口"})
@Slf4j
public class LoginRestApi {

    @Autowired
    private WebUtil webUtil;
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private AdminRoleService adminRoleService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserAdminRService userAdminRService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private MenusService menusService;
    @Autowired
    private Audience audience;
    @Value(value = "${isRememberMeExpiresSecond}")
    private int isRememberMeExpiresSecond;
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private ProxyFeignClient proxyFeignClient;
    @Autowired
    private SysParamsService sysParamsService;
    @Autowired
    private MessageSmsService messageSmsService;
    @Value(value = "${tokenHead}")
    private String tokenHead;

    @Value(value = "${tokenHeader}")
    private String tokenHeader;

    @ApiOperation(value = "用户登录", notes = "用户登录")
    @PostMapping("/login")
    public String login(HttpServletRequest request,
                        @ApiParam(name = "username", value = "用户名或邮箱或手机号") @RequestParam(name = "username", required = false) String username,
                        @ApiParam(name = "password", value = "密码") @RequestParam(name = "password", required = false) String password,
                        @ApiParam(name = "isRememberMe", value = "是否记住账号密码") @RequestParam(name = "isRememberMe", required = false, defaultValue = "false") Boolean isRememberMe) {

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return ResultUtil.result(SysConf.ERROR, "账号或密码不能为空");
        }
        String ip = IpUtils.getIpAddr(request);
        String limitCount = redisUtil.get(RedisConf.LOGIN_LIMIT + RedisConf.SEGMENTATION + ip);
        if (StringUtils.isNotEmpty(limitCount)) {
            Integer tempLimitCount = Integer.valueOf(limitCount);
            if (tempLimitCount >= Constants.NUM_FIVE) {
                return ResultUtil.result(SysConf.ERROR, "密码输错次数过多,已被锁定30分钟");
            }
        }
        Boolean isEmail = CheckUtils.checkEmail(username);
        Boolean isMobile = CheckUtils.checkMobileNumber(username);
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        if (isEmail) {
            queryWrapper.eq(SQLConf.EMAIL, username);
        } else if (isMobile) {
            queryWrapper.eq(SQLConf.MOBILE, username);
        } else {
            queryWrapper.eq(SQLConf.USER_NAME, username);
        }
        Admin admin = adminService.getOne(queryWrapper);
        if (admin == null) {
            // 设置错误登录次数
            return ResultUtil.result(SysConf.ERROR, String.format(MessageConf.LOGIN_ERROR, setLoginCommit(request)));
        }
        // 对密码进行加盐加密验证，采用SHA-256 + 随机盐【动态加盐】 + 密钥对密码进行加密
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean isPassword = encoder.matches(password, admin.getPassWord());
        if (!isPassword) {
            //密码错误，返回提示
            return ResultUtil.result(SysConf.ERROR, String.format(MessageConf.LOGIN_ERROR, setLoginCommit(request)));
        }
        int ownerType = 0;
        String ownerUid = null;
        String roleName = "暂停使用";
        if (StringUtils.isEmpty(admin.getDefaultUid())) {
            List<AdminRoleVO> list = adminRoleService.getMyFullRoleList(admin.getUid());
            if (list.size() > 0) {
                AdminRoleVO adminRoleVO = list.get(0);
                roleName = adminRoleVO.getRoleName();
                ownerType = adminRoleVO.getOwnerType();
                ownerUid = adminRoleVO.getOwnerUid();
                admin.setOwnerType(ownerType);
                admin.setDefaultUid(ownerUid);
                adminService.updateById(admin);
            } else {
                throw new RuntimeException("此用户没有任何角色");
            }
        }
        ownerType = admin.getOwnerType();
        ownerUid = admin.getDefaultUid();
        long expiration = isRememberMe ? isRememberMeExpiresSecond : audience.getExpiresSecond();
        long nowMillis = System.currentTimeMillis();
        long expMillis = nowMillis + (expiration * 1000);
        String jwtToken;
        jwtToken = jwtTokenUtil.createJWT(admin.getUserName(),
                admin.getUid(),
                roleName,
                audience.getClientId(),
                audience.getName(),
                ownerType,
                ownerUid,
                nowMillis,
                expMillis,
                audience.getBase64Secret());
        String token = tokenHead + jwtToken;
        Map<String, Object> result = new HashMap<>(Constants.NUM_ONE);
        result.put(SysConf.TOKEN, token);

//进行登录相关操作
        Integer count = admin.getLoginCount() + 1;
        admin.setLoginCount(count);
        admin.setLastLoginIp(IpUtils.getIpAddr(request));
        admin.setLastLoginTime(new Date());
        admin.updateById();
// 设置token到validCode，用于记录登录用户
        admin.setValidCode(token);
// 设置tokenUid，【主要用于换取token令牌，防止token直接暴露到在线用户管理中】
        admin.setTokenUid(StringUtils.getUUID());
        admin.setRoleName(roleName);
// 添加在线用户到Redis中【设置过期时间】
        adminService.addOnlineAdmin(admin, expiration);
        Map resultData = new HashMap();
        resultData.put("token", tokenHead + admin.getTokenUid());
        return ResultUtil.result(SysConf.SUCCESS, resultData);
    }


    @ApiOperation(value = "微信登录sessionId生成器", notes = "微信登录sessionId生成器", response = String.class)
    @GetMapping(value = "/getWxLoginSessionId")
    public String getWxLoginSessionId() {
        String wxSessionId = StringUtils.getUUID();
        //通过随机数字生成sessionId;
        JSONObject wxSession = new JSONObject();
        wxSession.put("status", "1");
        redisUtil.setEx(RedisConf.WX_SESSION_ID + RedisConf.SEGMENTATION + tokenHead + wxSessionId, wxSession.toJSONString(), 5, TimeUnit.MINUTES);
        return ResultUtil.result(SysConf.SUCCESS, wxSessionId);
    }

    @ApiOperation(value = "微信登录手机授权", notes = "微信登录手机授权", response = String.class)
    @GetMapping(value = "/wxLoginByCode")
    @Transactional
    public String wxLoginByCode(HttpServletRequest request, @ApiParam(name = "code", value = "code", required = true) @RequestParam(name = "code", required = true) String code,
                                @ApiParam(name = "sessionId", value = "sessionId", required = true) @RequestParam(name = "sessionId", required = true) String sessionId) {

        /*
        redis的锁机制，保证同一时间的第二次访问不会读取到被锁住的数据
         */
        String wxSession = redisUtil.get(RedisConf.WX_SESSION_ID + RedisConf.SEGMENTATION + tokenHead + sessionId);
        Map result = new HashMap();
        if (wxSession == null) {
            result.put("code", "9999");
            result.put("msg", "二维码已过期");
            return ResultUtil.result(SysConf.SUCCESS, result);
        }

        JSONObject wxSessionJson = JSONObject.parseObject(wxSession);
        if (!wxSessionJson.get("status").equals("1")) {
            result.put("code", "9998");
            result.put("msg", "二维码已使用");
            return ResultUtil.result(SysConf.SUCCESS, result);
        }
        wxSessionJson.put("status", "2");//正在登录
        redisUtil.set(RedisConf.WX_SESSION_ID + RedisConf.SEGMENTATION + tokenHead + sessionId, wxSessionJson.toJSONString());
        String openId = null;
        String accessToken = null;
        /***
         * 通过微信服务接口获得openId
         */
        String jsonStrOpenId = proxyFeignClient.getOpenId(code);
        try {
            JSONObject jsonOpenId = JSONObject.parseObject(jsonStrOpenId);
            openId = jsonOpenId.getString("openId");
            accessToken = jsonOpenId.getString("accessToken");
            if (openId == null) throw new RuntimeException("openId获取失败");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "9997");
            result.put("msg", jsonStrOpenId);
            return ResultUtil.result(SysConf.SUCCESS, result);
        }
        /***
         * 通过openId登录，查询用户表是否存在，不存在则创建新的用户信息
         * select user.uid,admin.uid from user left join useradminr …… left join admin where user.wechat=openId
         *
         * 如果useUid是空，那就没这个用户
         * 如果adminUid时空，有这个用户但是没有绑定管理员
         */
        UserAdminRVO userAdminRVO = new UserAdminRVO();
        userAdminRVO.setPageSize(100L);
        userAdminRVO.setCurrentPage(1L);
        userAdminRVO.setWeChat(openId);
        Admin admin = null;//通过openId连表查询admin信息
        IPage<UserAdminRVO> pageList = userAdminRService.getPageList(userAdminRVO);
        UserVO userVO = new UserVO();
        UserAdminRVO uar = null;
        if (pageList.getRecords().size() >= 1) {
            uar = pageList.getRecords().get(0);
            if (uar.getAdminUid() == null) {
                wxSessionJson.put("userUid", uar.getUserUid());//用户保存到session中，便于用户的管理员绑定；
                wxSessionJson.put("status", "3");//登录完成
                redisUtil.setEx(RedisConf.WX_SESSION_ID + RedisConf.SEGMENTATION + tokenHead + sessionId, wxSessionJson.toJSONString(), 10, TimeUnit.MINUTES);
                result.put("code", "0001");
                result.put("msg", "新用户登录，请先绑定操作员手机号");
                return ResultUtil.result(SysConf.SUCCESS, result);
            } else {
                admin = adminService.getById(uar.getAdminUid());
                /***
                 * 执行登录流程 参考 @PostMapping("/login")
                 */
                String roleName = "暂停使用";
                long expiration = audience.getExpiresSecond();
                long nowMillis = System.currentTimeMillis();
                long expMillis = nowMillis + (expiration * 1000);
                Role role = new Role();
                if (admin.getDefaultUid() != null) {
                    QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("owner_uid", admin.getDefaultUid());
                    List<Role> list = roleService.list(queryWrapper);
                    if (list.size() > 0) {
                        role = list.get(0);
                    }
                } else {
                    role = null;
                }
                String jwtToken;
                jwtToken = jwtTokenUtil.createJWT(
                        admin.getUserName(),
                        admin.getUid(),
                        roleName,
                        audience.getClientId(),
                        audience.getName(),
                        (role == null ? null : role.getOwnerType()),
                        (role == null ? null : role.getOwnerUid()),
                        nowMillis,
                        expMillis,
                        audience.getBase64Secret());
                String token = tokenHead + jwtToken;
                result = new HashMap<>(Constants.NUM_ONE);
                result.put(SysConf.TOKEN, token);

//进行登录相关操作
                Integer count = admin.getLoginCount() + 1;
                admin.setLoginCount(count);
                admin.setLastLoginIp(IpUtils.getIpAddr(request));
                admin.setLastLoginTime(new Date());
                admin.updateById();
// 设置token到validCode，用于记录登录用户
                admin.setValidCode(token);
// 设置tokenUid，【主要用于换取token令牌，防止token直接暴露到在线用户管理中】
                admin.setTokenUid(StringUtils.getUUID());
//        admin.setRole(roles.get(0));
// 添加在线用户到Redis中【设置过期时间】
                adminService.addOnlineAdmin(admin, expiration);
                Map resultData = new HashMap();
                wxSessionJson.put("token", tokenHead + admin.getTokenUid());//将登录以后的token保存起来，等待pc网页读取后登录；
                wxSessionJson.put("status", "3");//登录完成
                redisUtil.setEx(RedisConf.WX_SESSION_ID + RedisConf.SEGMENTATION + tokenHead + sessionId, wxSessionJson.toJSONString(), 10, TimeUnit.MINUTES);
                result.put("code", "0000");
                result.put("data", uar);
                result.put("token", tokenHead + admin.getTokenUid());
                return ResultUtil.result(SysConf.SUCCESS, result);
            }
        } else {
            userVO.setWeChat(openId);
            String jsonStrUserInfo = proxyFeignClient.getUserInfo(openId, accessToken);
            try {
                JSONObject jsonUserInfo = JSONObject.parseObject(jsonStrUserInfo);
                userVO.setNickName(jsonUserInfo.getString("nickName"));
                userVO.setAvatar(jsonUserInfo.getString("headImgurl"));
                userVO.setUserName("用户" + jsonUserInfo.getString("openId").substring(jsonUserInfo.getString("openId").length() - 8, jsonUserInfo.getString("openId").length() - 1));
                userVO.setGender(Integer.valueOf(jsonUserInfo.getString("sex")));
            } catch (Exception e) {
                e.printStackTrace();
                result.put("code", "9997");
                result.put("msg", jsonStrOpenId);
                return ResultUtil.result(SysConf.SUCCESS, result);
            }
            UserVO checkUserVO = userService.getUserWeChat(openId);
            if (checkUserVO == null) {
                userService.add(userVO);
                wxSessionJson.put("userUid", userVO.getUid());//用户保存到session中，便于用户的管理员绑定；
            } else {
                wxSessionJson.put("userUid", checkUserVO.getUid());//用户保存到session中，便于用户的管理员绑定；
            }
            wxSessionJson.put("status", "3");//登录完成
            redisUtil.setEx(RedisConf.WX_SESSION_ID + RedisConf.SEGMENTATION + tokenHead + sessionId, wxSessionJson.toJSONString(), 10, TimeUnit.MINUTES);
            result.put("code", "0001");
            result.put("msg", "新用户登录，请先绑定操作员手机号");
            return ResultUtil.result(SysConf.SUCCESS, result);
        }
    }

    @ApiOperation(value = "微信登录PC查询", notes = "微信登录PC查询", response = String.class)
    @GetMapping(value = "/wxLoginBySession")
    @Transactional
    public String wxLoginBySession(@ApiParam(name = "sessionId", value = "sessionId", required = true) @RequestParam(name = "sessionId", required = true) String sessionId) {
        String wxSession = redisUtil.get(RedisConf.WX_SESSION_ID + RedisConf.SEGMENTATION + tokenHead + sessionId);
        Map result = new HashMap();
        if (wxSession == null) {
            result.put("code", "9999");
            result.put("msg", "二维码已过期");
            return ResultUtil.result(SysConf.SUCCESS, result);
        }
        JSONObject wxSessionJson = JSONObject.parseObject(wxSession);
        if (wxSessionJson.get("status").equals("1")) {
            result.put("code", "0001");
            result.put("msg", "二维码正在授权");
            return ResultUtil.result(SysConf.SUCCESS, result);
        } else if (wxSessionJson.get("status").equals("2")) {
            result.put("code", "0001");
            result.put("msg", "正在核查绑定信息");
            return ResultUtil.result(SysConf.SUCCESS, result);
        } else if (wxSessionJson.get("status").equals("3")) {
            result.put("code", "0000");
            result.put("token", wxSessionJson.get("token"));
            result.put("userUid", wxSessionJson.get("userUid") == null ? "空" : "请从服务器测换取");
            return ResultUtil.result(SysConf.SUCCESS, result);
        } else {
            result.put("code", "9999");
            result.put("msg", "未知异常");
            return ResultUtil.result(SysConf.SUCCESS, result);
        }
    }


    @ApiOperation(value = "切换公司", notes = "切换公司")
    @PostMapping("/changeComMer")
    public String changeComMer(HttpServletRequest request,
                               @ApiParam(name = "ownerType", value = "公司类型") @RequestParam(name = "ownerType") Integer ownerType,
                               @ApiParam(name = "ownerUid", value = "公司代码") @RequestParam(name = "ownerUid") String ownerUid) {

        /***
         * 找到目前的token
         * 创建新的token并初始化
         * 作废旧token
         * 保存新token
         * 数据库更新default_uid
         * */
        AdminVO me = adminService.getMe();

        String authHeader = request.getHeader(tokenHeader);
        String tokenId = authHeader.substring(tokenHead.length());
        String token = redisUtil.get(com.zrwl.poscloud.xo.global.RedisConf.LOGIN_UUID_KEY + com.zrwl.poscloud.xo.global.RedisConf.SEGMENTATION + tokenId);
        String onlineAdmin = redisUtil.get(RedisConf.LOGIN_TOKEN_KEY + RedisConf.SEGMENTATION + token);
        OnlineAdmin oldOnlineAdmin = JsonUtils.jsonToPojo(onlineAdmin, OnlineAdmin.class);
        String keyPrefix = com.zrwl.poscloud.xo.global.RedisConf.LOGIN_TOKEN_KEY + com.zrwl.poscloud.xo.global.RedisConf.SEGMENTATION;
        redisUtil.delete(keyPrefix + token);
        long nowMillis = System.currentTimeMillis();
        long expMillis = nowMillis + (isRememberMeExpiresSecond * 1000);
        String jwtToken;
        jwtToken = jwtTokenUtil.createJWT(me.getUserName(),
                me.getUid(),
                "",
                audience.getClientId(),
                audience.getName(),
                ownerType,
                ownerUid,
                nowMillis,
                expMillis,
                audience.getBase64Secret());
        String newToken = tokenHead + jwtToken;
        Map<String, Object> result = new HashMap<>(Constants.NUM_ONE);
        result.put(SysConf.TOKEN, newToken);

//进行登录相关操作
        AdminVO adminVO = me;
        Integer count = adminVO.getLoginCount() + 1;
        adminVO.setLoginCount(count);
        adminVO.setLastLoginIp(IpUtils.getIpAddr(request));
        adminVO.setLastLoginTime(new Date());
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminVO, admin);
        admin.updateById();
// 设置token到validCode，用于记录登录用户
        adminVO.setValidCode(newToken);
        adminVO.setTokenUid(tokenId);
// 添加在线用户到Redis中【设置过期时间】
        Long exp = (long) audience.getExpiresSecond() * 1000;
        try {
            Long expire = DateUtils.dateToStamp(oldOnlineAdmin.getExpireTime()).longValue();
            exp = expire - new Date().getTime();
        } catch (Exception e) {

        }
        BeanUtils.copyProperties(adminVO, admin);
        adminService.addOnlineAdmin(admin, exp / 1000);
//刪除按钮权限redis
        redisUtil.delete(RedisConf.ADMIN_VISIT_MENU + SysConf.REDIS_SEGMENTATION + adminVO.getUid());
//更新当前的OwneUid
//删除getMe的redis缓存
        redisUtil.delete(RedisConf.ADMIN_INFO + RedisConf.SEGMENTATION + (tokenHead + tokenId));
        me.setDefaultUid(ownerUid);
        me.setOwnerType(ownerType);
        Admin adminMe = new Admin();
        BeanUtils.copyProperties(me, adminMe);
        adminService.updateById(adminMe);

        return ResultUtil.result(SysConf.SUCCESS, new Object());
    }

    @ApiOperation(value = "用户信息", notes = "用户信息", response = String.class)
    @GetMapping(value = "/info")
    public String info(HttpServletRequest request,
                       @ApiParam(name = "token", value = "token令牌", required = false) @RequestParam(name = "token", required = false) String token) {

        Map<String, Object> map = new HashMap<>(Constants.NUM_THREE);
        if (request.getAttribute(SysConf.ADMIN_UID) == null) {
            return ResultUtil.result(SysConf.ERROR, "token用户过期");
        }
        Admin admin = adminService.getById(request.getAttribute(SysConf.ADMIN_UID).toString());
        map.put(SysConf.TOKEN, token);
        map.put(SysConf.AVATAR,admin.getAvatar());
/***
 * 2021年7月9日 优化登录，此处的role返回前台的意义存疑，暂时放弃

 List<String> roleUid = new ArrayList<>();
 List<AdminRole> adminRoleList = adminRoleService.getmyRoleList(admin.getUid());
 for (AdminRole items : adminRoleList) {
 roleUid.add(items.getRoleUid());
 }
 //        roleUid.add(admin.getRoleUid());
 Collection<Role> roleList = roleService.listByIds(roleUid);
 */

//        map.put(SysConf.ROLES, roleList);
        List roles = new ArrayList();
        roles.add(new Role());
        map.put(SysConf.ROLES, roles);
        Map adminInfo = new HashMap();
        // 避免数据泄露，只返回前台需要的adminMe数据
        AdminVO adminMe = adminService.getMe();
        adminInfo.put("companyType", adminMe.getCompanyType());
        adminInfo.put("ownerType", adminMe.getOwnerType());
        map.put("adminInfo", adminInfo);
        return ResultUtil.result(SysConf.SUCCESS, map);
    }

//    @ApiOperation(value = "获取当前用户的菜单", notes = "获取当前用户的菜单", response = String.class)
//    @GetMapping(value = "/getMenu")
//    public String getMenu(HttpServletRequest request) {
//
//        Collection<CategoryMenu> categoryMenuList = new ArrayList<>();
//        Admin admin = adminService.getById(request.getAttribute(SysConf.ADMIN_UID).toString());
//
//        List<String> roleUid = new ArrayList<>();
//        roleUid.add(admin.getRoleUid());
//        Collection<Role> roleList = roleService.listByIds(roleUid);
//
//        List<String> categoryMenuUids = new ArrayList<>();
//
//        roleList.forEach(item -> {
//            String caetgoryMenuUids = item.getCategoryMenuUids();
//            String[] uids = caetgoryMenuUids.replace("[", "").replace("]", "").replace("\"", "").split(",");
//            for (int a = 0; a < uids.length; a++) {
//                categoryMenuUids.add(uids[a]);
//            }
//
//        });
//        categoryMenuList = categoryMenuService.listByIds(categoryMenuUids);
//
//        // 从三级级分类中查询出 二级分类
//        List<CategoryMenu> buttonList = new ArrayList<>();
//        Set<String> secondMenuUidList = new HashSet<>();
//        categoryMenuList.forEach(item -> {
//            // 查询二级分类
//            if (item.getMenuType() == EMenuType.MENU && item.getMenuLevel() == SysConf.TWO) {
//                secondMenuUidList.add(item.getUid());
//            }
//            // 从三级分类中，得到二级分类
//            if (item.getMenuType() == EMenuType.BUTTON && StringUtils.isNotEmpty(item.getParentUid())) {
//                // 找出二级菜单
//                secondMenuUidList.add(item.getParentUid());
//                // 找出全部按钮
//                buttonList.add(item);
//            }
//        });
//
//        Collection<CategoryMenu> childCategoryMenuList = new ArrayList<>();
//        Collection<CategoryMenu> parentCategoryMenuList = new ArrayList<>();
//        List<String> parentCategoryMenuUids = new ArrayList<>();
//
//        if (secondMenuUidList.size() > 0) {
//            childCategoryMenuList = categoryMenuService.listByIds(secondMenuUidList);
//        }
//
//        childCategoryMenuList.forEach(item -> {
//            //选出所有的二级分类
//            if (item.getMenuLevel() == SysConf.TWO) {
//
//                if (StringUtils.isNotEmpty(item.getParentUid())) {
//                    parentCategoryMenuUids.add(item.getParentUid());
//                }
//            }
//        });
//
//        if (parentCategoryMenuUids.size() > 0) {
//            parentCategoryMenuList = categoryMenuService.listByIds(parentCategoryMenuUids);
//        }
//
//        List<CategoryMenu> list = new ArrayList<>(parentCategoryMenuList);
//
//        //对parent进行排序
//        Map<String, Object> map = new HashMap<>(Constants.NUM_THREE);
//        Collections.sort(list);
//        map.put(SysConf.PARENT_LIST, list);
//        map.put(SysConf.SON_LIST, childCategoryMenuList);
//        map.put(SysConf.BUTTON_LIST, buttonList);
//        return ResultUtil.result(SysConf.SUCCESS, map);
//    }


    @ApiOperation(value = "获取当前用户的菜单", notes = "获取当前用户的菜单", response = String.class)
    @GetMapping(value = "/getMenu")
    public String getMenu(HttpServletRequest request) {
// 解析出请求者的ID和用户名
        String adminUid = request.getAttribute(SysConf.ADMIN_UID).toString();
        // 管理员能够访问的路径
        String visitUrlStr = redisUtil.get(RedisConf.PRESENT_ADMIN_VISIT_MENU + RedisConf.SEGMENTATION + adminUid);
        if (StringUtils.isNotEmpty(visitUrlStr)) {
            Map<String, Object> map;
            // 从Redis中获取
            map = (Map<String, Object>) JsonUtils.jsonToMap(visitUrlStr, String.class);
            return ResultUtil.result(SysConf.SUCCESS, map);
        } else {
            //获取当前用户信息
            String ownerUid = null;
            Integer ownerType = null;
            if (request.getAttribute(SysConf.OWNER_UID) != null && request.getAttribute(SysConf.OWNER_TYPE) != null) {
                ownerUid = request.getAttribute(SysConf.OWNER_UID).toString();
                ownerType = (Integer) request.getAttribute(SysConf.OWNER_TYPE);
            }
            //获取当前用户所有权限
            Collection<MenusVO> menusList = new ArrayList<>();
//        Admin admin = adminService.getById(request.getAttribute(SysConf.ADMIN_UID).toString());
            List<String> roleUid = new ArrayList<>();
            List<AdminRole> adminRoleList = adminRoleService.getmyRoleList(request.getAttribute(SysConf.ADMIN_UID).toString());
            for (AdminRole items : adminRoleList) {
                roleUid.add(items.getRoleUid());
            }

//条件查询当前机构下 且拥有权限的角色列表  理论上可以和上面的步骤用1条sql处理，但是性能估计差不多，暂时不优化
            QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(SysConf.STATUS, EStatus.ENABLE);
            if (ownerType != null && ownerUid != null) {
                queryWrapper.eq(SysConf.OWNER_UID, ownerUid);
                queryWrapper.eq(SysConf.OWNER_TYPE, ownerType);
            }
            queryWrapper.in("uid", roleUid);
            List<Role> rolesList = roleService.list(queryWrapper);
////遍历拥有权限得到完全集合
            List<String> MenuStringList = new ArrayList<>();
            List<MenusVO> rootMMM = new ArrayList<>();
            rolesList.forEach(item -> {
                String caetgoryMenuUids = item.getCategoryMenuUids();
                List<MenusVO> menusVOList = JSONObject.parseArray(caetgoryMenuUids, MenusVO.class);
                List<String> resultList = new ArrayList<>();
                Stack<MenusVO> stack = new Stack<>();
                MenusVO menusVO = new MenusVO();
                for (MenusVO items : menusVOList) {
                    if (items.getName().equals("PC端")) {
                        menusVO = items;
                        rootMMM.add(items);
                        break;
                    }
                }

                while (menusVO.getChildrenList() != null && menusVO.getChildrenList().size() != 0) {
                    for (MenusVO items : menusVO.getChildrenList()) {
                        stack.push(items);
                        if (items.getChildrenList() == null || items.getChildrenList().size() == 0) {
                            resultList.add(items.getUid());
                            stack.pop();
                        }
                    }
                    if (stack.size() != 0) {
                        menusVO = stack.pop();
                        resultList.add(menusVO.getUid());
                    } else {
                        break;
                    }
                }
                MenuStringList.addAll(resultList);
            });

//利用MAP对功能集合去重
            Map<String, String> temporaryMap = new HashMap<>();
            temporaryMap.put(MenuStringList.get(0), MenuStringList.get(0));
            for (String items : MenuStringList) {
                if (!temporaryMap.containsKey(items)) {
                    temporaryMap.put(items, items);
                } else {

                }
            }

            MenuStringList.clear();
            for (String items : temporaryMap.values()) {
                MenuStringList.add(items);
            }
//            生成树结构
            Collection<Menus> temporaryMenusList = menusService.listByIds(MenuStringList);
            List<MenusVO> temporary2MenusList = new ArrayList<>();
            rootMMM.get(0).getChildrenList().clear();
            menusList.add(rootMMM.get(0));
            Map<String, MenusVO> temporaryMenusMap = new HashMap();

            temporaryMenusMap.put(rootMMM.get(0).getUid(), rootMMM.get(0));

            for (Menus items : temporaryMenusList) {
                MenusVO menusVO = new MenusVO();
                menusVO.setChildrenList(new ArrayList<>());
                BeanUtils.copyProperties(items, menusVO);
                temporaryMenusMap.put(menusVO.getUid(), menusVO);
                temporary2MenusList.add(menusVO);
            }
            for (MenusVO items : temporary2MenusList) {
                if (temporaryMenusMap.containsKey(items.getSuperUid())) {
                    temporaryMenusMap.get(items.getSuperUid()).getChildrenList().add(items);
                }
            }

            //未使用（可废弃）
//        menusList = menusService.mergeTreeList(MenuStringList);

// 从三级级分类中查询出 二级分类
            List<Menus> buttonList = new ArrayList<>();
            Set<String> secondMenuUidList = new HashSet<>();

            menusList.forEach(item -> {
                // 查询根是否没有子节点
                if (item.getChildrenList() != null && item.getChildrenList().size() != 0) {
                    item.getChildrenList().forEach(item2 -> {
                        // 查询一级菜单的子节点
                        if (item2.getChildrenList() != null && item2.getChildrenList().size() != 0) {
                            item2.getChildrenList().forEach(item3 -> {
                                // 查询二级菜单
                                if (item3.getMenuType() == EMenuType.MENU) {
                                    secondMenuUidList.add(item3.getUid());
                                }
                            });
                        }
                    });
                }
            });

// 找出全部按钮
            Stack<MenusVO> stack = new Stack<>();
            MenusVO menusVO = new MenusVO();
            for (MenusVO items : menusList) {
                if (items.getName().equals("PC端")) {
                    menusVO = items;
                }
            }
            while (menusVO.getChildrenList() != null && menusVO.getChildrenList().size() != 0) {
                for (MenusVO items : menusVO.getChildrenList()) {
                    stack.push(items);
                    if (items.getChildrenList() == null || items.getChildrenList().size() == 0) {
                        if (items.getMenuType() == EMenuType.BUTTON) {
                            Menus entity = new Menus();
                            BeanUtils.copyProperties(items, entity);
                            buttonList.add(entity);
                        }
                        stack.pop();
                    }
                }
                if (stack.size() != 1) {
                    menusVO = stack.pop();
                } else {
                    stack.pop();
                    break;
                }
            }

            Collection<Menus> childMenusList = new ArrayList<>();
            Collection<Menus> parentMenusList = new ArrayList<>();
            List<String> parentMenusUids = new ArrayList<>();

            if (secondMenuUidList.size() > 0) {
                childMenusList = menusService.listByIds(secondMenuUidList);
            }

            childMenusList.forEach(item -> {
                //选出所有的二级分类的上层UID
                if (StringUtils.isNotEmpty(item.getSuperUid())) {
                    parentMenusUids.add(item.getSuperUid());
                }
            });

            if (parentMenusUids.size() > 0) {
                parentMenusList = menusService.listByIds(parentMenusUids);
            }

            List<Menus> list = new ArrayList<>(parentMenusList);

//对parent进行排序
            Map<String, Object> map = new HashMap<>(Constants.NUM_THREE);
            Collections.sort(list);
            map.put(SysConf.PARENT_LIST, list);
            map.put(SysConf.SON_LIST, childMenusList);
            map.put(SysConf.BUTTON_LIST, buttonList);
            // 将访问URL存储到Redis中
            redisUtil.setEx(RedisConf.PRESENT_ADMIN_VISIT_MENU + SysConf.REDIS_SEGMENTATION + adminUid, JsonUtils.objectToJson(map), 1, TimeUnit.HOURS);
            return ResultUtil.result(SysConf.SUCCESS, map);
        }
    }

    @ApiOperation(value = "获取网站名称", notes = "获取网站名称", response = String.class)
    @GetMapping(value = "/getWebSiteName")
    public String getWebSiteName() {
        return ResultUtil.successWithData(sysParamsService.getSysParamsValueByKey("SYS_NAME"));
    }

    @ApiOperation(value = "获取网站名称", notes = "获取网站名称", response = String.class)
    @GetMapping(value = "/checkUnlockName")
    public String checkUnlockName(String pwd) {
        String result = "error";
        String unLockPwd = sysParamsService.getSysParamsValueByKey("UNLOCK_PWD");
        if (StringUtils.isNotEmpty(unLockPwd) && unLockPwd.equals(pwd)) {
            result = "success";
        }
        return ResultUtil.successWithData(result);
    }

    @ApiOperation(value = "获取登录方式", notes = "获取登录方式", response = String.class)
    @GetMapping(value = "/getLoginMethod")
    public String getLoginMethod() {
        String result = "error";
        String wx_login = sysParamsService.getSysParamsValueByKey("WX_LOGIN");
        String sms_login = sysParamsService.getSysParamsValueByKey("SMS_LOGIN");
        Map<String, String> map = new HashMap<>();
        map.put("wx_login", wx_login);
        map.put("sms_login", sms_login);
        return ResultUtil.successWithData(map);
    }

    @ApiOperation(value = "退出登录", notes = "退出登录", response = String.class)
    @PostMapping(value = "/logout")
    public String logout() {
        ServletRequestAttributes attribute = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attribute.getRequest();
        if (request.getAttribute(SysConf.TOKEN) == null) return ResultUtil.successWithMessage("token已过期，退出成功");
        String token = request.getAttribute(SysConf.TOKEN).toString();
        if (StringUtils.isEmpty(token)) {
            return ResultUtil.result(SysConf.ERROR, MessageConf.OPERATION_FAIL);
        } else {
            // 获取在线用户信息
            token = token.substring(tokenHead.length());
            String tokenUUKEY = redisUtil.get(RedisConf.LOGIN_UUID_KEY + RedisConf.SEGMENTATION + token);
            String adminJson = redisUtil.get(RedisConf.LOGIN_TOKEN_KEY + RedisConf.SEGMENTATION + tokenUUKEY);
            if (StringUtils.isNotEmpty(adminJson)) {
                OnlineAdmin onlineAdmin = JsonUtils.jsonToPojo(adminJson, OnlineAdmin.class);
                String tokenUid = onlineAdmin.getTokenId();
                // 移除Redis中的TokenUid
                redisUtil.delete(RedisConf.LOGIN_UUID_KEY + RedisConf.SEGMENTATION + tokenUid);
            }
            // 移除Redis中的用户
            redisUtil.delete(RedisConf.LOGIN_TOKEN_KEY + RedisConf.SEGMENTATION + tokenUUKEY);
            redisUtil.delete(RedisConf.ADMIN_INFO + RedisConf.SEGMENTATION + (tokenHead + token));
            String adminUid = request.getAttribute(SysConf.ADMIN_UID).toString();
            if (adminUid != null) {
                redisUtil.delete(RedisConf.ADMIN_VISIT_MENU + RedisConf.SEGMENTATION + adminUid);
                redisUtil.delete(RedisConf.PRESENT_ADMIN_VISIT_MENU + RedisConf.SEGMENTATION + adminUid);
            }
            return ResultUtil.result(SysConf.SUCCESS, MessageConf.OPERATION_SUCCESS);
        }
    }

    /**
     * 设置登录限制，返回剩余次数
     * 密码错误五次，将会锁定10分钟
     *
     * @param request
     */
    private Integer setLoginCommit(HttpServletRequest request) {
        String ip = IpUtils.getIpAddr(request);
        String count = redisUtil.get(RedisConf.LOGIN_LIMIT + RedisConf.SEGMENTATION + ip);
        Integer surplusCount = 5;
        if (StringUtils.isNotEmpty(count)) {
            Integer countTemp = Integer.valueOf(count) + 1;
            surplusCount = surplusCount - countTemp;
            redisUtil.setEx(RedisConf.LOGIN_LIMIT + RedisConf.SEGMENTATION + ip, String.valueOf(countTemp), 10, TimeUnit.MINUTES);
        } else {
            surplusCount = surplusCount - 1;
            redisUtil.setEx(RedisConf.LOGIN_LIMIT + RedisConf.SEGMENTATION + ip, "1", 30, TimeUnit.MINUTES);
        }
        return surplusCount;
    }

    @ApiOperation(value = "绑定操作员", notes = "绑定操作员", response = String.class)
    @PostMapping("/boundOperator")
    public String boundOperator(HttpServletRequest request,
                                @ApiParam(name = "sessionId", value = "sessionId") @RequestParam(name = "sessionId", required = false) String sessionId,
                                @ApiParam(name = "mobileCode", value = "mobileCode") @RequestParam(name = "mobileCode", required = false) String mobileCode,
                                @ApiParam(name = "validCode", value = "validCode") @RequestParam(name = "validCode", required = false) String validCode) {
        String wxSessionJson = redisUtil.get(RedisConf.WX_SESSION_ID + RedisConf.SEGMENTATION + tokenHead + sessionId);
        if (StringUtils.isEmpty(wxSessionJson)) {
            return ResultUtil.result(SysConf.ERROR, "认证已超时，请重新扫码");
        }
        QueryWrapper<Admin> queryWrapperAdmin = new QueryWrapper<>();
        queryWrapperAdmin.eq(SysConf.STATUS, EStatus.ENABLE);
        queryWrapperAdmin.eq("mobile", mobileCode);
        Admin admin = null;
        admin = adminService.getOne(queryWrapperAdmin);
        UserAdminRVO userAdminRVO = new UserAdminRVO();
        if (admin == null) {
            return ResultUtil.result(SysConf.ERROR, "未找到操作员");
        } else {
            userAdminRVO.setAdminUid(admin.getUid());
            JSONObject wxSession = JSONObject.parseObject(wxSessionJson);
            userAdminRVO.setUserUid(wxSession.getString("userUid"));
            userAdminRService.add(userAdminRVO);
            /***
             * 执行登录流程 参考 @PostMapping("/login")
             */
            String roleName = "暂停使用";
            long expiration = audience.getExpiresSecond();
            long nowMillis = System.currentTimeMillis();
            long expMillis = nowMillis + (expiration * 1000);
            Role role = new Role();
            if (admin.getDefaultUid() != null) {
                QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("owner_uid", admin.getDefaultUid());
                List<Role> list = roleService.list(queryWrapper);
                if (list.size() > 0) {
                    role = list.get(0);
                }
            } else {
                role = null;
            }
            String jwtToken;
            jwtToken = jwtTokenUtil.createJWT(
                    admin.getUserName(),
                    admin.getUid(),
                    roleName,
                    audience.getClientId(),
                    audience.getName(),
                    (role == null ? null : role.getOwnerType()),
                    (role == null ? null : role.getOwnerUid()),
                    nowMillis,
                    expMillis,
                    audience.getBase64Secret());
            String token = tokenHead + jwtToken;
            Map result = new HashMap<>(Constants.NUM_ONE);
            result.put(SysConf.TOKEN, token);

//进行登录相关操作
            Integer count = admin.getLoginCount() + 1;
            admin.setLoginCount(count);
            admin.setLastLoginIp(IpUtils.getIpAddr(request));
            admin.setLastLoginTime(new Date());
            admin.updateById();
// 设置token到validCode，用于记录登录用户
            admin.setValidCode(token);
// 设置tokenUid，【主要用于换取token令牌，防止token直接暴露到在线用户管理中】
            admin.setTokenUid(StringUtils.getUUID());
//        admin.setRole(roles.get(0));
// 添加在线用户到Redis中【设置过期时间】
            adminService.addOnlineAdmin(admin, expiration);
            Map resultData = new HashMap();
            redisUtil.delete(RedisConf.WX_SESSION_ID + RedisConf.SEGMENTATION + tokenHead + sessionId);
            result.put("code", "0000");
            result.put("token", tokenHead + admin.getTokenUid());
            return ResultUtil.result(SysConf.SUCCESS, result);
        }
    }

    @ApiOperation(value = "获取短信验证码", notes = "获取短信验证码", response = String.class)
    @PostMapping("/obtainSMSCode")
    public String obtainSMSCode(HttpServletRequest request, @ApiParam(name = "mobileCode", value = "mobileCode") @RequestParam(name = "mobileCode", required = true) String mobileCode) {
        if (StringUtils.isEmpty(mobileCode) || StringUtils.isEmpty(mobileCode.trim())) {
            return ResultUtil.errorWithMessage("手机号不能为空");
        }

        int number = messageSmsService.getCurrentSMS(mobileCode);
        if (number >= 10) {
            return ResultUtil.errorWithMessage("获取验证码错误,今天获取次数已上限");
        }
        MessageSmsVO messageSmsVO = new MessageSmsVO();
        messageSmsVO.setMobile(mobileCode);
        messageSmsVO.setContent(RandomUtils.genSimplePWD() + "##10");
        return messageSmsService.add(messageSmsVO, EMessageModelType.SMS_VERIFICATION_CODE);
    }

    @ApiOperation(value = "操作员手机号登录", notes = "操作员手机号登录", response = String.class)
    @PostMapping("/loginOperatorForMobile")
    public String loginOperatorForMobile(HttpServletRequest request,
                                         @ApiParam(name = "mobileCode", value = "mobileCode") @RequestParam(name = "mobileCode", required = true) String mobileCode,
                                         @ApiParam(name = "pwd", value = "pwd") @RequestParam(name = "pwd", required = false) String pwd,
                                         @ApiParam(name = "validCode", value = "validCode") @RequestParam(name = "validCode", required = false) String validCode) {
        if (StringUtils.isEmpty(mobileCode) || StringUtils.isEmpty(mobileCode.trim())) {
            return ResultUtil.errorWithMessage("手机号不能为空");
        }
        if ((StringUtils.isEmpty(validCode) || StringUtils.isEmpty(validCode.trim()))
                && StringUtils.isEmpty(pwd)) {
            return ResultUtil.errorWithMessage("参数不能为空");
        }
        QueryWrapper<Admin> queryWrapperAdmin = new QueryWrapper<>();
        queryWrapperAdmin.eq(SysConf.STATUS, EStatus.ENABLE);
        queryWrapperAdmin.eq("mobile", mobileCode);
        Admin admin = null;
        admin = adminService.getOne(queryWrapperAdmin);
        UserAdminRVO userAdminRVO = new UserAdminRVO();
        if (admin == null) return ResultUtil.result(SysConf.ERROR, "操作员不存在");
        if (StringUtils.isNotEmpty(pwd)) {
            String ip = IpUtils.getIpAddr(request);
            String limitCount = redisUtil.get(RedisConf.LOGIN_LIMIT + RedisConf.SEGMENTATION + ip);
            if (StringUtils.isNotEmpty(limitCount)) {
                Integer tempLimitCount = Integer.valueOf(limitCount);
                if (tempLimitCount >= Constants.NUM_FIVE) {
                    return ResultUtil.result(SysConf.ERROR, "密码输错次数过多,已被锁定30分钟");
                }
            }
            QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
            // 对密码进行加盐加密验证，采用SHA-256 + 随机盐【动态加盐】 + 密钥对密码进行加密
            PasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean isPassword = encoder.matches(pwd, admin.getPassWord());
            if (!isPassword) {
                //密码错误，返回提示
                return ResultUtil.result(SysConf.ERROR, String.format(MessageConf.LOGIN_ERROR, setLoginCommit(request)));
            }
        } else {
            MessageSms messageSms = null;
            try {
                //校验不通过将抛出异常
                messageSms = messageSmsService.verificationCode(mobileCode, validCode);
                messageSms.setToUid(admin.getUid());
                messageSms.setUpdateTime(new Date());
                messageSms.updateById();
            } catch (RuntimeException r) {
                return ResultUtil.result(SysConf.ERROR, r.getMessage());
            }
        }


        userAdminRVO.setAdminUid(admin.getUid());
        String roleName = "暂停使用";
        long expiration = audience.getExpiresSecond();
        long nowMillis = System.currentTimeMillis();
        long expMillis = nowMillis + (expiration * 1000);
        Role role = new Role();
        if (admin.getDefaultUid() != null) {
            QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("owner_uid", admin.getDefaultUid());
            List<Role> list = roleService.list(queryWrapper);
            if (list.size() > 0) {
                role = list.get(0);
            }
        } else {
            role = null;
        }
        String jwtToken;
        jwtToken = jwtTokenUtil.createJWT(
                admin.getUserName(),
                admin.getUid(),
                roleName,
                audience.getClientId(),
                audience.getName(),
                (role == null ? null : role.getOwnerType()),
                (role == null ? null : role.getOwnerUid()),
                nowMillis,
                expMillis,
                audience.getBase64Secret());
        String token = tokenHead + jwtToken;
        Map result = new HashMap<>(Constants.NUM_ONE);
        result.put(SysConf.TOKEN, token);

//进行登录相关操作
        Integer count = admin.getLoginCount() + 1;
        admin.setLoginCount(count);
        admin.setLastLoginIp(IpUtils.getIpAddr(request));
        admin.setLastLoginTime(new Date());
        admin.updateById();
// 设置token到validCode，用于记录登录用户
        admin.setValidCode(token);
// 设置tokenUid，【主要用于换取token令牌，防止token直接暴露到在线用户管理中】
        admin.setTokenUid(StringUtils.getUUID());
//        admin.setRole(roles.get(0));
// 添加在线用户到Redis中【设置过期时间】
        adminService.addOnlineAdmin(admin, expiration);
        result.put("code", "0000");
        result.put("token", tokenHead + admin.getTokenUid());
        return ResultUtil.result(SysConf.SUCCESS, result);
    }

    @ApiOperation(value = "通过手机号验证是否有管理员", notes = "通过手机号验证是否有管理员", response = String.class)
    @PostMapping("/getAdminByMobile")
    public String getAdminByMobile(HttpServletRequest request,
                                   @ApiParam(name = "mobileCode", value = "mobileCode") @RequestParam(name = "mobileCode", required = false) String mobileCode,
                                   @ApiParam(name = "validCode", value = "validCode") @RequestParam(name = "validCode", required = false) String validCode) {
        MessageSms messageSms = null;
        try {
            messageSms = messageSmsService.verificationCode(mobileCode, validCode);
        } catch (RuntimeException r) {
            return ResultUtil.result(SysConf.ERROR, r.getMessage());
        }
        QueryWrapper<Admin> queryWrapperAdmin = new QueryWrapper<>();
        queryWrapperAdmin.eq(SysConf.STATUS, EStatus.ENABLE);
        queryWrapperAdmin.eq("mobile", mobileCode);
        Admin admin = null;
        admin = adminService.getOne(queryWrapperAdmin);
        UserAdminRVO userAdminRVO = new UserAdminRVO();
        if (admin == null) {
            return ResultUtil.result(SysConf.ERROR, "未找到操作员");
        } else {
            messageSms.setToUid(admin.getUid());
            messageSms.setUpdateTime(new Date());
            messageSms.updateById();
            return ResultUtil.successWithData(admin.getUserName());
        }

    }

    @ApiOperation(value = "密码重置", notes = "通过手机号验证是否有管理员", response = String.class)
    @PostMapping("/resetPassword")
    public String resetPassword(HttpServletRequest request,
                                @ApiParam(name = "username", value = "username") @RequestParam(name = "username", required = false) String username,
                                @ApiParam(name = "password", value = "password") @RequestParam(name = "password", required = false) String password) {
        QueryWrapper<Admin> queryWrapperAdmin = new QueryWrapper<>();
        queryWrapperAdmin.eq(SysConf.STATUS, EStatus.ENABLE);
        queryWrapperAdmin.eq("user_name", username);
        Admin admin = null;
        admin = adminService.getOne(queryWrapperAdmin);
        if (admin == null) {
            return ResultUtil.errorWithMessage("非法操作");
        } else {
            if (StringUtils.isEmpty(password) || StringUtils.isEmpty(password)) {
                return ResultUtil.errorWithMessage(com.zrwl.poscloud.xo.global.MessageConf.PARAM_INCORRECT);
            }
            PasswordEncoder encoder = new BCryptPasswordEncoder();
            admin.setPassWord(encoder.encode(password));
            admin.setUpdateTime(new Date());
            admin.updateById();
            return ResultUtil.successWithMessage(com.zrwl.poscloud.xo.global.MessageConf.UPDATE_SUCCESS);
        }

    }
}